<?php

namespace App\Http\Controllers\Manage;

use App\Rule;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Cases;
use App\Casecate;
use Illuminate\Support\Facades\Storage;
use Validator;
use Illuminate\Support\Facades\Redirect;
use Session;

class CaseController extends Controller
{
    /**
     * @var int 数据表id
     */
    public $table_id = 3;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $casecates = Casecate::all();
        $cases = Cases::orderBy('rank', 'desc')->orderBy('id', 'desc')->paginate(20);
        return view('manage/case/index', compact('casecates', 'cases'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $casecates = Casecate::all();
        $cases = Cases::all();
        return view('manage/case/create', compact('casecates', 'cases'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $savePath  = null;
        $saveTinyPath = null;
        $file_height = null;

        $input = $request->only('category', 'title', 'idea', 'rank');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'idea' => 'required',
            'rank' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'idea' => '创意理念',
            'rank' => '权重'
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            // 查找重复
            if(Cases::whereTitle($input['title'])->first()) {
                return redirect()->back()->withInput()->withErrors('案例名称已经存在');
            }
            else {
                if($request->hasFile('file')) {
                    $file = $request->file('file');
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传文件有误！');
                    }
                    $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                    $savePath = 'files/' . $newFileName;
                    $bytes = Storage::put(
                        $savePath,
                        file_get_contents($file->getRealPath())
                    );
                    $img = getimagesize('upload/' . $savePath);
                    $img = explode(' ', $img[3])[1];
                    $file_height = substr($img, 8, strlen($img) - 9);

                    if(!Storage::exists($savePath)) {
                        return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                    }
                }

                if($request->hasFile('tinyfile')) {
                    $file = $request->file('tinyfile');
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传导读小图有误！');
                    }
                    $newTinyFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                    $saveTinyPath = 'files/' . $newTinyFileName;
                    $bytes = Storage::put(
                        $saveTinyPath,
                        file_get_contents($file->getRealPath())
                    );
                    if(!Storage::exists($saveTinyPath)) {
                        return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                    }
                }
                if(Cases::insert([
                    'category' => $request->input('category'),
                    'title' => $request->input('title'),
                    'keyword' => $request->input('keyword'),
                    'description' => $request->input('description'),
                    'rank' => $request->input('rank'),
                    'background' => $request->input('background'),
                    'idea' => $request->input('idea'),
                    'file' => $savePath,
                    'author' => $request->input('author'),
                    'tinyfile' => $saveTinyPath,
                    'status' => $request->input('status'),
                    'file_height' => $file_height
                ])) {
                    return Redirect::to("manage/case");
                }
                else  {
                    return redirect()->back()->withInput()->withErrors('添加失败');
                }
            }
        }
        return redirect("manage/case/index");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $status = Cases::whereId($id)->pluck('status');
        $status = $status[0];
        if($status == 0) {
            if(Cases::whereId($id)->update(['status' => 1])) {
                return redirect()->back()->withInput()->withSuccess('案例ID:'.$id.' 状态已启用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('案例ID:'.$id.' 状态启用失败');
            }
        }
        else {
            if(Cases::whereId($id)->update(['status' => 0])) {
                return redirect()->back()->withInput()->withSuccess('案例ID:'.$id.' 状态已禁用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('案例ID:'.$id.' 状态禁用失败');
            }
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $casecates = Casecate::all();
        $cases = Cases::whereId($id)->first();
        return view('manage/case/edit', compact('casecates', 'cases'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $savePath  = null;
        $saveTinyPath = null;
        $file_height = Cases::whereId($id)->pluck('file_height')[0];

        $input = $request->only('category', 'title', 'idea', 'rank');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'idea' => 'required',
            'rank' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'idea' => '创意理念',
            'rank' => '权重',
        ];
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            $savePath = null;
            if($request->hasFile('file')) {
                $file = $request->file('file');
                if(!$file->isValid()) {
                    return redirect()->back()->withInput()->withErrors('上传文件有误！');
                }
                $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                $savePath = 'files/' . $newFileName;
                $bytes = Storage::put(
                    $savePath,
                    file_get_contents($file->getRealPath())
                );

                $img = getimagesize('upload/' . $savePath);
                $img = explode(' ', $img[3])[1];
                $file_height = substr($img, 8, strlen($img) - 9);

                if(!Storage::exists($savePath)) {
                    return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                }
            }
            else {
                $savePath = Cases::whereId($id)->pluck('file')[0];
            }


            if($request->hasFile('tinyfile')) {
                $file = $request->file('tinyfile');
                if(!$file->isValid()) {
                    return redirect()->back()->withInput()->withErrors('上传导读小图有误！');
                }
                $newTinyFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();
                $saveTinyPath = 'files/' . $newTinyFileName;
                $bytes = Storage::put(
                    $saveTinyPath,
                    file_get_contents($file->getRealPath())
                );
                if(!Storage::exists($saveTinyPath)) {
                    return redirect()->back()->withInput()->withErrors('保存上传文件失败');
                }
            }
            else {
                $saveTinyPath = Cases::whereId($id)->pluck('tinyfile')[0];
            }


            if(Cases::where('id', $id)->update([
                'category' => $request->input('category'),
                'title' => $request->input('title'),
                'keyword' => $request->input('keyword'),
                'description' => $request->input('description'),
                'rank' => $request->input('rank'),
                'background' => $request->input('background'),
                'idea' => $request->input('idea'),
                'file' => $savePath,
                'status' => $request->input('status'),
                'tinyfile' => $saveTinyPath,
                'author' => $request->input('author'),
                'file_height' => $file_height
            ])) {
                return Redirect::to("manage/case");
            }
            else  {
                return redirect()->back()->withInput()->withErrors('更新失败');
            }

        }
        return redirect("manage/case/index");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     *
     * @return array|null
     */
    public function destroy($id)
    {
        $callback = null;
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $file = Cases::whereId($id)->pluck("file");
        if(Cases::destroy($id)) {
            if($file) {
                if(Storage::delete($file[0])) {
                    $callback = [
                        'code' => 100,
                        'msg' => '删除成功！'
                    ];
                }
                else {
                    $callback = [
                        'code' => 100,
                        'msg' => '文章删除成功，图片删除失败！图片地址' . $file
                    ];
                }
            }
            else {
                $callback = [
                    'code' => 100,
                    'msg' => '删除成功！'
                ];
            }
        }
        else {
            $callback = [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
        return $callback;
    }
    /**
     * 批量删除案例
     * @param Request $request
     * @return array|null|string
     */
    public function casedel (Request $request) {
        $callback = null;
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $checkboxes = $request->input('chkbox');
        if($request->input('chkbox') == null) {
            return $callback = [
                'code'=> 101,
                'msg' => "请选择删除内容"
            ];
        }
        for($i = 0; $i<sizeof($checkboxes); $i++) {
            $id = $checkboxes[$i];
            if(Cases::destroy($id)) {
                $callback = [
                    'code' => 101,
                    'msg' => $callback['msg'] . '删除ID：' . $id . '成功, '
                ];
            }
            else {
                $callback .= '删除ID：' . $id . '失败';
            }
        }
        return $callback;
    }
    /**
     * 分类查询案例
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function casesearch(Request $request)
    {
        $casecates = Casecate::all();
        $title = $request->input('table_search');
        if ($title == null) {
            return redirect()->back()->withInput()->withErrors('请输入要搜索关键字！');
        } else {
            $result = Cases::where('title', 'like', '%' . $title . '%')->get();
            if ($result) {
                return view('manage/batch/searcase', compact('result', 'casecates'));
            }
        }
    }
    /**
     * 分类状态设置案例
     * @param $id
     * @return mixed
     */
    public function casestatus($id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $status = Cases::whereId($id)->pluck('status');
        $status = $status[0];
        if($status == 0) {
            if(Cases::whereId($id)->update(['status' => 1])) {
                return redirect('manage/case')->withSuccess('文章ID:'.$id.' 状态已启用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('文章ID:'.$id.' 状态启用失败');
            }
        }
        else {
            if(Cases::whereId($id)->update(['status' => 0])) {
                return redirect('manage/case')->withSuccess('文章ID:'.$id.' 状态已禁用');
            }
            else {
                return redirect()->back()->withInput()->withErrors('文章ID:'.$id.' 状态禁用失败');
            }
        }
    }
}
